import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import { indexOf } from 'lodash';
import {
  Row,
  Col,
  Card,
  Form,
  Select,
  Button,
  message,
  Popconfirm,
  Tabs,
  Table,
  Dropdown,
  Menu,
  notification,
  Alert,
  Icon,
} from 'antd';

const TabPane = Tabs.TabPane;
import { convertProjectCode } from './components/toolkit';
import PlaceForm from './components/PlaceForm';
import CaipanForm from './components/CaipanForm';
import MatchForm from './components/SelectMatchForm';
import SelectCaipanForm from './components/SelectCaipanForm';
import { tableChangePagination } from './components/Pagination';

import styles from './TableList.less';
import { isNull } from 'util';

const FormItem = Form.Item;
const { Option } = Select;

@connect(({ zubie, gameList, place, loading }) => ({
  zubie,
  gameList,
  place,
  loading: loading.models.zubie,
}))
@Form.create()
export default class MatchView extends PureComponent {
  state = {
    modalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
  };

  componentDidMount() {
    const { dispatch, location } = this.props;
    const pathArray = location.pathname.split('/');
    const id = pathArray[3];
    this.setState({
      id,
    });

    dispatch({
      type: 'zubie/clean',
      payload: {},
    });

    dispatch({
      type: 'gameList/findById',
      payload: id,
      callback: () => {
        dispatch({
          type: 'zubie/queryAllZubieForGame',
          callback: () => {
            this.props.dispatch({
              type: 'place/findGameCaipan',
              payload: {},
            });
            const {
              zubie: { curZubie, zubieList },
            } = this.props;
            //console.log(curZubie)
            if (!curZubie) {
              return;
            }
            const zubieMap = zubieList.map(value => {
              return value.code;
            });
            if (indexOf(zubieMap, curZubie) > -1) {
              this.onSelectZubie(curZubie);
            } else {
              this.props.dispatch({
                type: 'zubie/changeState',
                payload: {
                  curZubie: null,
                  curZubieObj: {},
                },
              });
            }
          },
        });

        // this.props.dispatch({
        //   type: 'place/findPlaceData',
        // });
      },
    });
  }

  onSelectZubie = value => {
    this.props.dispatch({
      type: 'zubie/changeState',
      payload: {
        curZubie: value,
      },
    });

    this.props.dispatch({
      type: 'place/findPlaceForGame',
      payload: {
        zubieCode: value,
      },
    });

    this.props.dispatch({
      type: 'place/findTimeForGame',
      payload: {
        zubieCode: value,
      },
    });

    this.props.dispatch({
      type: 'zubie/queryZubieByCode',
      payload: value,
    });

    this.props.dispatch({
      type: 'place/findPlaceData',
      payload: { zubieCode: value },
    });

    this.props.dispatch({
      type: 'place/findMatchForPlace',
      payload: value,
    });

    this.props.dispatch({
      type: 'zubie/queryPhase',
      payload: value,
    });
    this.props.dispatch({
      type: 'zubie/queryNotSetPlaceGame',
      payload: {
        zubieCode: value,
      },
    });

    this.props.dispatch({
      type: 'place/findZhixuForKongchang',
      payload: {
        zubieCode: value,
      },
    });

    this.setState({
      curPhase: null,
    });
  };

  handleCaipanAdd = fields => {
    this.props.dispatch({
      type: 'place/addCaipan',
      payload: fields,
      callback: () => {
        //this.caipanHandleModalVisible(false)
        this.props.dispatch({
          type: 'place/changeState',
          payload: { curCaipan: {} },
        });
        this.props.dispatch({
          type: 'place/findGameCaipan',
          payload: {},
        });
        message.success('裁判添加成功');
      },
    });
    //this.CaipanHandleModalVisible();
  };

  handleCaipanFindByTel = tel => {
    this.props.dispatch({
      type: 'place/findCaipanByTel',
      payload: tel,
    });
  };

  handleCaipanDelete = id => {
    this.props.dispatch({
      type: 'place/deleteCaipan',
      payload: id,
      callback: () => {
        this.props.dispatch({
          type: 'place/findGameCaipan',
          payload: {},
        });
        message.success('裁判删除成功');
      },
    });
  };

  caipanhandler = values => {
    this.handleCaipanAdd(values);
  };

  caipanHandleModalVisible = flag => {
    this.setState({
      caipanModalVisible: !!flag,
    });
    this.props.dispatch({
      type: 'place/changeState',
      payload: { curCaipan: {} },
    });
  };

  showCaipanModifyModal = data => {
    this.setState({
      caipanModalVisible: true,
    });
  };

  handlePlaceAdd = fields => {
    this.props.dispatch({
      type: 'place/addPlace',
      payload: fields,
      callback: () => {
        message.success('场地添加成功');
        this.props.dispatch({
          type: 'place/findZhixuForKongchang',
          payload: {
            zubieCode: this.props.zubie.curZubie,
          },
        });
      },
    });
    //this.placeHandleModalVisible();
  };

  handlePlaceModify = fields => {
    this.props.dispatch({
      type: 'place/modifyPlace',
      payload: fields,
      callback: () => {
        message.success('场地修改成功');
      },
    });
  };

  handlePlaceDelete = id => {
    this.props.dispatch({
      type: 'place/deletePlace',
      payload: id,
      callback: () => {
        message.success('场地删除成功');
      },
    });
  };

  placehandler = values => {
    if (values.id) {
      this.handlePlaceModify(values);
    } else {
      this.handlePlaceAdd(values);
    }
  };

  placeHandleModalVisible = flag => {
    this.setState({
      placeModalVisible: !!flag,
    });
  };

  showPlaceModifyModal = data => {
    this.setState({
      placeModalVisible: true,
    });
  };

  showmatchModal = (curPlaceCode, curPlaceName) => {
    this.setState({
      matchModalVisible: true,
      curPlaceCode,
      curPlaceName,
    });
  };

  matchHandler = values => {
    this.props.dispatch({
      type: 'zubie/setKongchang',
      payload: {
        id: values.id,
        placeCode: this.state.curPlaceCode,
        placeName: this.state.curPlaceName,
        zubieCode: values.zubieCode,
      },
      callback: () => {
        message.success('设置成功');
        this.props.dispatch({
          type: 'place/findZhixuForKongchang',
          payload: {
            zubieCode: values.zubieCode,
          },
        });
        this.props.dispatch({
          type: 'place/findPlaceData',
          payload: { zubieCode: values.zubieCode },
        });
        this.props.dispatch({
          type: 'zubie/queryNotSetPlaceGame',
          payload: {
            zubieCode: values.zubieCode,
          },
        });
      },
    });
    this.setState({
      curPlaceCode: null,
      curChangxuCode: null,
      curPlaceName: null,
    });
  };

  matchHandleModalVisible = flag => {
    this.setState({
      matchModalVisible: !!flag,
    });
  };

  showCaipanSelectModal = matchCode => {
    this.setState({
      caipanSelectModalVisible: true,
      matchCode,
    });
  };

  caipanSelectHandler = values => {
    console.log(values);
    this.props.dispatch({
      type: 'place/setCaipan',
      payload: {
        matchCode: this.state.matchCode,
        caipanCode: values.code,
        caipanRole: values.caipanRole,
      },
      callback: () => {
        message.success('设置成功');
        this.props.dispatch({
          type: 'place/findZhixuForKongchang',
          payload: {
            zubieCode: this.props.zubie.curZubie,
          },
        });
      },
    });
    this.setState({
      matchCode: null,
    });
  };

  caipanSelectHandleModalVisible = flag => {
    this.setState({
      caipanSelectModalVisible: !!flag,
    });
  };

  finishGame = item => {
    this.props.dispatch({
      type: 'zubie/finishMatch',
      payload: {
        code: item.code,
        zubieCode: item.zubieCode,
      },
      callback: () => {
        message.success('比赛已完成');
        this.props.dispatch({
          type: 'place/findPlaceData',
          payload: { zubieCode: item.zubieCode },
        });
        this.props.dispatch({
          type: 'place/findZhixuForKongchang',
          payload: {
            zubieCode: item.zubieCode,
          },
        });
        this.props.dispatch({
          type: 'zubie/queryNotSetPlaceGame',
          payload: {
            zubieCode: item.zubieCode,
          },
        });
      },
    });
  };

  cancelSetPlace = item => {
    // if(item.zubieCode !== this.props.zubie.curZubie){
    //   notification.error({
    //     message: `非本组别的赛事，不能取消。如果要取消请选择赛事所在的组别`,
    //     //description: errortext,
    //   });
    //   return
    // }

    this.props.dispatch({
      type: 'zubie/cancelSetPlace',
      payload: {
        code: item.code,
        zubieCode: item.zubieCode,
      },
      callback: () => {
        message.success('取消成功');
        this.props.dispatch({
          type: 'place/findPlaceData',
          payload: { zubieCode: item.zubieCode },
        });
        this.props.dispatch({
          type: 'place/findZhixuForKongchang',
          payload: {
            zubieCode: item.zubieCode,
          },
        });
        this.props.dispatch({
          type: 'zubie/queryNotSetPlaceGame',
          payload: {
            zubieCode: item.zubieCode,
          },
        });
      },
    });
  };

  showItemMenu = item => {
    return (
      <Menu>
        <Menu.Item>
          <Popconfirm
            title="是否确定取消分配。 "
            onConfirm={() => this.cancelSetPlace(item)}
            okText="Yes"
            cancelText="No"
          >
            <Button>取消分配</Button>
          </Popconfirm>
          <Popconfirm
            title="是否确定完成比赛。 "
            onConfirm={() => this.finishGame(item)}
            okText="Yes"
            cancelText="No"
          >
            <Button>完成比赛</Button>
          </Popconfirm>
        </Menu.Item>
      </Menu>
    );
  };

  renderSimpleForm() {
    const {
      zubie: { curZubieObj, zubieList, curZubie, phaseList },
    } = this.props;
    return (
      <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
        <Col md={8} sm={24}>
          <FormItem label="请选择组别">
            <Select
              placeholder="未选择"
              style={{ width: '100%' }}
              onChange={this.onSelectZubie}
              value={curZubie}
            >
              {zubieList.map(element => {
                if (element.enabled)
                  return (
                    <Option key={'OP' + element.code} value={element.code}>
                      {convertProjectCode(element.projectCode) + ' - ' + element.zubieName}
                    </Option>
                  );
              })}
            </Select>
          </FormItem>
        </Col>
        {!curZubie && (
          <Col md={4} sm={16}>
            <FormItem>
              <Alert
                style={{ flex: 1 }}
                message="请选择一个组别"
                type="error"
                icon={<Icon type="left" />}
                showIcon={true}
              />
            </FormItem>
          </Col>
        )}
        <Col md={8} sm={24}>
          <Button style={{ marginRight: 5 }} onClick={() => this.showPlaceModifyModal()}>
            场地管理
          </Button>
          <Button style={{ marginRight: 5 }} onClick={() => this.showCaipanModifyModal()}>
            裁判管理
          </Button>
        </Col>
      </Row>
    );
  }

  renderJiemu = item => (
    <div
      style={{
        textAlign: 'center',
        backgroundColor: item.zubieCode === this.props.zubie.curZubie ? '#1890FF' : '',
        color: item.zubieCode === this.props.zubie.curZubie ? '#ffffff' : '',
      }}
    >
      <div
        style={{ borderStyle: 'none none solid none', borderWidth: '1px', borderColor: '#e8e8e8' }}
      >
        {item.bisaiId}
      </div>
      <div>
        {convertProjectCode(item.projectCode)} {item.zubieName} 第{item.round}轮
      </div>
      <div
        style={{
          display: 'flex',
          borderStyle: 'solid none none none',
          borderWidth: '1px',
          borderColor: '#e8e8e8',
        }}
      >
        <span
          style={{
            flex: 1,
            borderStyle: 'none solid none none',
            borderWidth: '1px',
            borderColor: '#e8e8e8',
          }}
        >
          {item.gamePosName1}
        </span>
        <span style={{ flex: 1 }}>{item.gamePosName2}</span>
      </div>
      {this.renderJiemuAthlete(item)}
      <div style={{ display: 'flex' }}>
        <span
          style={{
            flex: 1,
            borderStyle: 'none solid none none',
            borderWidth: '1px',
            borderColor: '#e8e8e8',
          }}
        >
          {item.team1}
        </span>
        <span style={{ flex: 1 }}>{item.team2}</span>
      </div>
    </div>
  );

  renderKongchang = item => (
    <Dropdown overlay={this.showItemMenu(item)} trigger={['contextMenu']} placement="bottomCenter">
      <div style={{ textAlign: 'center' }}>
        <div
          style={{
            borderStyle: 'solid solid solid solid',
            borderWidth: '1px',
            borderColor: '#e8e8e8',
            fontWeight: 'bold',
          }}
        >
          {item.bisaiId}
          {item.caipanName && ` (裁判:${item.caipanName})`}
        </div>
        <div
          style={{
            borderStyle: 'none solid none solid',
            borderWidth: '1px',
            borderColor: '#e8e8e8',
          }}
        >
          {convertProjectCode(item.projectCode)} {item.zubieName} 第{item.round}轮
        </div>
        <div
          style={{
            display: 'flex',
            borderStyle: 'solid solid none none',
            borderWidth: '1px',
            borderColor: '#e8e8e8',
          }}
        >
          <span
            style={{
              flex: 1,
              borderStyle: 'none solid none solid',
              borderWidth: '1px',
              borderColor: '#e8e8e8',
            }}
          >
            {item.gamePosName1}
          </span>
          <span style={{ flex: 1 }}>{item.gamePosName2}</span>
        </div>
        <div
          style={{
            borderStyle: 'none solid none solid',
            borderWidth: '1px',
            borderColor: '#e8e8e8',
          }}
        >
          {this.renderJiemuAthlete(item)}
        </div>
        <div style={{ display: 'flex' }}>
          <span
            style={{
              flex: 1,
              borderStyle: 'none solid solid solid',
              borderWidth: '1px',
              borderColor: '#e8e8e8',
            }}
          >
            {item.team1}
          </span>
          <span
            style={{
              flex: 1,
              borderStyle: 'none solid solid none',
              borderWidth: '1px',
              borderColor: '#e8e8e8',
            }}
          >
            {item.team2}
          </span>
        </div>
        <div>{this.renderScore(item.scoreList)}</div>
        <div>{this.renderCaipan(item.caipanList)}</div>
      </div>
    </Dropdown>
  );

  renderScore = scoreList => {
    const scoreDiv = scoreList.map(value => (
      <div style={{ textAlign: 'center', width: '100%' }}>
        <div style={{ fontWeight: 'bold' }}>第{value.seq}局</div>
        <div
          style={{
            display: 'flex',
            borderStyle: 'solid solid none none',
            borderWidth: '1px',
            borderColor: '#e8e8e8',
          }}
        >
          <span
            style={{
              flex: 1,
              borderStyle: 'none solid none solid',
              borderWidth: '1px',
              borderColor: '#e8e8e8',
            }}
          >
            {value.startTime ? value.startTime : '未设置'}
          </span>
          <span style={{ flex: 1 }}>{value.endTime ? value.endTime : '未设置'}</span>
        </div>
        <div
          style={{
            display: 'flex',
            borderStyle: 'solid solid solid none',
            borderWidth: '1px',
            borderColor: '#e8e8e8',
          }}
        >
          <span
            style={{
              flex: 1,
              borderStyle: 'none solid none solid',
              borderWidth: '1px',
              borderColor: '#e8e8e8',
            }}
          >
            {value.score1 ? value.score1 : 0}
          </span>
          <span style={{ flex: 1 }}>{value.score2 ? value.score2 : 0}</span>
        </div>
      </div>
    ));
    return scoreDiv;
  };

  renderCaipan = caipanList => (
    <div
      style={{
        textAlign: 'center',
        width: '100%',
        borderStyle: 'none none solid none',
        borderWidth: '1px',
        borderColor: '#e8e8e8',
      }}
    >
      <div style={{ fontWeight: 'bold' }}>裁判员</div>
      {caipanList.map(value => (
        <div
          style={{
            display: 'flex',
            borderStyle: 'solid solid none none',
            borderWidth: '1px',
            borderColor: '#e8e8e8',
          }}
        >
          <span
            style={{
              flex: 1,
              borderStyle: 'none solid none solid',
              borderWidth: '1px',
              borderColor: '#e8e8e8',
            }}
          >
            {this.convertCaipan(value.caipanRole)}
          </span>
          <span style={{ flex: 1 }}>{value.caipanName}</span>
        </div>
      ))}
    </div>
  );

  convertCaipan = value => {
    switch (value) {
      case 'umpire':
        return '主裁判';
      case 's-judge':
        return '发球裁判';
      case 't-judge':
        return '司线裁判';
    }
  };

  renderJiemuAthlete = item => {
    const userList1 = item.athlethList1.map((value, index, array) => {
      return value.userName;
    });

    const userList2 = item.athlethList2.map((value, index, array) => {
      return value.userName;
    });
    return (
      <div
        style={{
          display: 'flex',
          borderStyle: 'solid none solid none',
          borderWidth: '1px',
          borderColor: '#e8e8e8',
        }}
      >
        <div
          style={{
            flex: 1,
            borderStyle: 'none solid none none',
            borderWidth: '1px',
            borderColor: '#e8e8e8',
          }}
        >
          {userList1.join(',')}
        </div>
        <div style={{ flex: 1 }}>{userList2.join(',')}</div>
      </div>
    );
  };

  handleZhixuTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const params = tableChangePagination(pagination, filtersArg, sorter);
    (params.zubieCode = this.props.zubie.curZubie),
      this.props.dispatch({
        type: 'zubie/queryNotSetPlaceGame',
        payload: params,
      });
  };

  handleTabChange = value => {
    this.setState({
      curTab: value,
    });
  };

  renderCardAction = match =>
    match &&
    match.code && (
      <Dropdown.Button
        onClick={() => {
          this.showCaipanSelectModal(match.code);
        }}
        overlay={this.kongchangMenu(match)}
      >
        指派裁判
      </Dropdown.Button>
    );

  kongchangMenu = match => (
    <Menu>
      <Menu.Item key="video">
        <Icon type="video-camera" />
        投屏显示
      </Menu.Item>
      <Menu.Item
        key="jifen"
        onClick={() => window.open('/bgms/gameScore/jifenbiao/' + match.code, 'GET')}
      >
        <Icon type="file-text" />
        下载记分表
      </Menu.Item>
    </Menu>
  );

  render() {
    const {
      zubie: { curZubieObj, notSetPlaceGameList },
      loading,
      place: { placeList, zubiePlaceList, placeData, kongchangList, caipanList, curCaipan },
    } = this.props;
    const {
      placeModalVisible,
      caipanModalVisible,
      matchModalVisible,
      caipanSelectModalVisible,
    } = this.state;

    const placeMethod = {
      handleAdd: this.placehandler,
      handleModalVisible: this.placeHandleModalVisible,
    };

    const caipanMethod = {
      handleAdd: this.caipanhandler,
      handleModalVisible: this.caipanHandleModalVisible,
    };

    const caipanSelectMethod = {
      handleAdd: this.caipanSelectHandler,
      handleModalVisible: this.caipanSelectHandleModalVisible,
    };

    const matchMethod = {
      handleAdd: this.matchHandler,
      handleModalVisible: this.matchHandleModalVisible,
    };

    const jiemuChangdi = [];

    const columnJiemu = [
      {
        title: '日期',
        dataIndex: 'matchDate',
        width: 100,
        render: value => <span>{value.substring(0, 10)}</span>,
      },
      {
        title: '时间段',
        dataIndex: 'timePhase',
        width: 100,
        render: value => {
          switch (value) {
            case 'A':
              return '上午';
            case 'B':
              return '下午';
            case 'C':
              return '晚上';
          }
        },
      },
      {
        title: '场序',
        dataIndex: 'seq',
        width: 80,
      },
      {
        title: '场  地  名  称',
        children: jiemuChangdi,
      },
    ];

    const columnKongchang = [
      {
        title: '场  地  名  称',
        children: jiemuChangdi,
      },
    ];

    placeList.map(value => {
      jiemuChangdi.push({
        title: value.name,
        dataIndex: value.code,
        align: 'center',
        render: (item, row) => {
          if (item) {
            return this.renderJiemu(item);
          }
        },
      });
    });

    const topColResponsiveProps = {
      xs: 24,
      sm: 12,
      md: 12,
      lg: 12,
      xl: 6,
      style: { marginBottom: 24 },
    };

    return (
      <Fragment>
        <Card>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderSimpleForm()}</div>
            {curZubieObj && (
              <Tabs>
                <TabPane tab="控场" key="kongchangT">
                  <Row gutter={24}>
                    {kongchangList.map(value => (
                      <Col {...topColResponsiveProps}>
                        <Card
                          title={value.placeName}
                          headStyle={{ fontWeight: 'bold' }}
                          extra={this.renderCardAction(value)}
                          bodyStyle={{ textAlign: 'center' }}
                        >
                          {value.bisaiId ? (
                            this.renderKongchang(value)
                          ) : (
                            <Button
                              type="primary"
                              onClick={() => {
                                if (curZubieObj && curZubieObj.status === 'AC')
                                  this.showmatchModal(value.placeCode, value.placeName);
                                else message.error('抽签后才能分配场次');
                              }}
                            >
                              分配
                            </Button>
                          )}
                        </Card>
                      </Col>
                    ))}
                  </Row>
                </TabPane>

                <TabPane tab="场序表" key="jiemudan">
                  <Table
                    size="small"
                    loading={loading}
                    pagination={false}
                    bordered
                    dataSource={placeData}
                    columns={columnJiemu}
                  />
                </TabPane>
              </Tabs>
            )}
          </div>
        </Card>
        <PlaceForm
          {...placeMethod}
          modalVisible={placeModalVisible}
          gameCode={this.props.gameList.modifyItem.code}
          placeList={placeList}
          deleteMethod={this.handlePlaceDelete}
        />
        <CaipanForm
          {...caipanMethod}
          modalVisible={caipanModalVisible}
          caiapnList={caipanList}
          selectByTel={this.handleCaipanFindByTel}
          deleteMethod={this.handleCaipanDelete}
          curData={curCaipan}
        />

        <MatchForm
          {...matchMethod}
          modalVisible={matchModalVisible}
          matchList={notSetPlaceGameList ? notSetPlaceGameList : {}}
          onChange={this.handleZhixuTableChange}
        />
        <SelectCaipanForm
          {...caipanSelectMethod}
          modalVisible={caipanSelectModalVisible}
          caipanList={caipanList ? caipanList : []}
        />
      </Fragment>
    );
  }
}
